<?php
declare( strict_types = 0 );
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cache;
use app\model\OrderModel;
use app\model\CatModel;
use app\model\UserModel;
use app\model\DeptModel;
use app\model\DeliveryModel;
use app\Common;

class Order {
    //常用数据表内容 及常用字典

    var $cat = [];
    var $dept = [];
    var $users = [];
    var $bg;
    var $sys;
    var $stars = array( 0 => '', 1 => '★☆☆☆☆', 2 => '★★☆☆☆', 3 => '★★★☆☆', 4 => '★★★★☆', 5 => '★★★★★' );

    //[ 'name', 'english name', 'next statue', 'view name' ]
    var $status = array(
        '1' => array( '新单', 'New order', '2', '确认' ),
        '2' => array( '已确认', 'Checked', '3', '' ),

        '10' => array( '客户取消', '', '0', '' ),
        '20' => array( '管理员取消', '', 0, '' )
    );
    var $discount = [];
    var $payment = array( 'wx' => '微信', 'alipay' => '支付宝', 'cash' => '现金' );
    var $type = array( '1' => '客户下单', '2' => '转手订单' );
    var $status_delivery = array( '1' => '待确认', '2' => '已确认', '3' => '已取消' );

    //构造器

    public function __construct() {
        $catM = new CatModel();
        $this->cat = $catM->catTree( 1 );
        $um = new UserModel();
        $this->users = $um->getAll();
        $dm = new DeptModel();
        $this->dept = $dm->getAll();

        for ( $dis = 100; $dis > 50; $dis -= 5 ) {
            $this->discount[] = [ 'value' => $dis / 100, 'desc' => $dis . '%' ];
        }
        $this->sys = Db::table( 'sys' )->find( 1 );

    }

    //商品

    public function goods_list() {
        $list = Db::table( 'goods' )->where( 'status', 1 )->order( 'id' )->select()->toArray();
        return json( $list );
    }

    //订单流程中查询, 用不同的状态区分所处流程
    public function index( $status = '' ) {
        $uid = Session::get( 'logonid' );
        if ( empty( $uid ) )
        header( 'location:/index.php/login' );

        $all = Request::param();

        $sdate = !empty( $all[ 'sdate' ] ) ? $all[ 'sdate' ] : '';
        $edate = !empty( $all[ 'edate' ] ) ? $all[ 'edate' ] : date( 'Y-m-d', time() );
        if ( $edate < $sdate )
        return json( '日期错误！' );

        $view = '';
        if ( !empty( $all[ 'view' ] ) )
        $view = $all[ 'view' ];
        $st = !empty( $all[ 'status' ] ) ? $all[ 'status' ] : $status;

        //默认查询
        $query = Db::table( 'order' );
        if ( $st ) {
            $query->where( 'status', 'in', $st );
        }

        $query_arr = [];
        //处理分页其它参数

    $goods_name='';
    if(!empty($all['goods_name'])){
        $goods_name=trim($all['goods_name']);
        $query->where('goods_list','like','%'.$goods_name."%");
        $query_arr['goods_name']= $goods_name;
    }


    $po = '';
    if ( !empty( $all[ 'po' ] ) ) {
        $po = trim( $all[ 'po' ] );
        $query->where( 'order_no', 'like', '%' . $po . '%' );
        $query_arr[ 'po' ] = $all[ 'po' ];
    }

    $customer_id = '';
    if($uid==1){
        if ( !empty( $all[ 'customer' ] ) ) {
            $customer_id = trim( $all[ 'customer' ] );
            $query->where( 'user_id', $customer_id );
            $query_arr[ 'customer' ] = $customer_id;
        }        
    }else{
        $query->where( 'user_id', $uid );
        $query_arr[ 'customer' ] = $uid;
    }


    if ( !empty( $all[ 'sdate' ] ) ) {
        $query->where( 'create_time', '>=', trim( $sdate ) );
        $query_arr[ 'sdate' ] = $all[ 'sdate' ];
    }

    if ( !empty( $all[ 'edate' ] ) ) {
        $query->where( 'create_time', '<=', trim( $edate ).' 23:59:59' );
        $query_arr[ 'edate' ] = $all[ 'edate' ];
    }

    $list = $query->order( 'id desc' )->paginate( 15 )->toArray();
    $num_deliv = 0;
    $num_undeliv = 0;

    $query2 = '&'.http_build_query( $query_arr );

    foreach ( $list[ 'data' ] as &$kv ) {
        $kv[ 'status_name' ] = $this->status[ $kv[ 'status' ] ];
        $kv[ 'user_id_name' ] = $this->users[$kv['user_id']]['name'];
        $kv[ 'amount' ] = number_format( $kv[ 'amount' ]);
        $kv[ 'days_left' ] = common::time_format( strtotime( $kv['end_time'] )-time() );
    }

    //halt( $this->type );
    $sys = Session::get( 'sys' );
    $custs = Db::table( 'user' )->where( 'status', 1 )->column( 'id,name' );

    View::assign( [
        'sys' => $sys,
        'list' => $list,
        'status_list' => $this->status,
        'status' => $st,
        'po' => $po,
        'goods_name' =>$goods_name,
        'sdate'=>$sdate,
        'edate'=>$edate,
        'currency_symbol' => $this->sys[ 'currency_symbol' ],
        'query'=>$query2
    ] );

    return View::fetch( $view );

}

//订单流程操作, 传入id, status

public function order_check() {
    $uid = Session::get( 'logonid' );
    if ( !$uid )
    header( 'location:/index.php/login' );
    $all = Request::param();

    if ( empty( $all[ 'table' ] ) || empty( $all[ 'id' ] ) || empty( $all[ 'status' ] ) ) {
        return json( [ 'code' => 0, 'msg' => '无效的状态！' ] );
    }

    $res = Db::execute( 'update `'.$all[ 'table' ].'` set status=?,check_time=?,check_by=? where id=?', [ $all[ 'status' ], date( 'Y-m-d H:i:s' ), $uid, $all[ 'id' ] ] );

    return json( [ 'code' => $res ] );

}

//订单操作记录

public function order_log() {
    if ( !Session::get( 'logonid' ) )
    header( 'location:/index.php/login' );

    $all = Request::param();
    if ( empty( $all[ 'id' ] ) )
    return 'Invalid order id!';
    $id = $all[ 'id' ];

    $order = Db::table( 'order' )->find( $id );
    if ( !$order )
    return '无效的订单！';
    $order[ 'creater_name' ] = $this->users[ $order[ 'creater' ] ][ 'name' ];
    $order[ 'status_name' ] = $this->status[ $order[ 'status' ] ];

    $list = Db::table( 'order_log' )->where( 'order_id', $id )->select()->toArray();
    foreach ( $list as &$log ) {
        if ( $log[ 'creater' ] )
        $log[ 'creater_name' ] = $this->users[ $log[ 'creater' ] ][ 'name' ];
    }

    View::assign( [ 'order' => $order, 'list' => $list ] );
    return View::fetch( 'order_log' );
}

public function order_flow() {
    $sys = Db::table( 'sys' )->find( 1 );
    View::assign( [ 'list' => $this->status, 'sys' => $sys ] );
    return View::fetch();
}

public function get_status() {
    $uid = Session::get( 'logonid' );
    if ( !$uid ) {
        return header( 'location:/index.php/login' );
    }

    return json_encode( [ 'code' => 1, 'status' => $this->status ] );
}

//商品单下单
public function order_add() {
    $uid = Session::get( 'logonid' );
    if ( empty( $uid ) )
    header( 'location:/index.php/login/target/admin' );
    $all = Request::param();

    //无商品参数提交，表示是进入页面
    if (empty( $all['link_url'] ) ) {
        $ad = Db::table('goods')->find($all['id']);
        View::assign([
            'ad'=>$ad,
            'sdate'=>date('Y-m-d')
        ] );
        return View::fetch();
    }

    //处理商品, 价格
    $price = 0;
    $goods_list_str = [];
    $order_list = [];
    $qty = 1;

    //取得新的流水号order
    $om = new OrderModel();

    $g=Db::table('goods')->find($all['g_id']);
    if(!$g){
        return json(['code'=>0,'msg'=>'Error!']);
    }
    if(!empty($g['order_no'])){
        return json(['code'=>0,'msg'=>'下单失败!']);
    }

    $sdate=date('Y-m-d');
    if($all['edate']<$sdate) return json(['code'=>0,'msg'=>'日期选择错误！']);

    $days = (strtotime($all['edate'])-strtotime($sdate))/3600/24;
    $amount=$days*$g['price'];
    $user =Db::table('user')->find($uid);

    if($user['money']<$amount){
        return json(['code'=>0,'msg'=>'需要花费'.$amount.",余额:".$user['money'].",请联系管理员充值!"]);
    }

    //准备订单内容，写入订单并取得id号
    $order_no = date('YmdHis').rand(100,1000);
    $row = array(
        'type' => 1,
        'order_no' => $order_no,
        'create_time' => date( 'Y-m-d H:i:s' ),
        'qty'=>$days,
        'amount' => $amount,
        'status' => 2,
        'user_id' => $uid,
        'goods_list' => $g['name'].'x'.$days,
        'start_time' =>$sdate,
        'end_time' =>$all['edate'],
        'memo' => trim( $all[ 'memo' ]),
        'dept_id' => 1
    );
    $oid = $om->insertGetid( $row );

    Db::table('user')->save(array('id'=>$uid,'money'=>$user['money']-$row['amount']));

    if($oid){
        $goods = [
            'id'=>$g['id'],
            'order_id'=>$oid,
            'user_id'=>$uid,
            'start_time' =>$sdate,
            'end_time' =>$all['edate']
        ];
        $res =Db::table('goods')->save($goods);

        return json( [ 'code' => $res, 'msg' => '下单成功!' ] );
    }else{
        return json(['code'=>0,'msg'=>'下单失败!']);
    }
}

//订单明细表
public function order_list() {
    $uid = Session::get( 'logonid' );
    $all = Request::param();

    //无商品参数提交，表示是进入页面
    if ( empty( $all[ 'id' ] ) || empty( $uid ) ) {
        return json( [ 'code' => 0, 'msg' => '错误，请登录后重试！' ] );
    }

    $order = Db::table( 'order' )->find( $all[ 'id' ] );
    //halt( $this->users[ $order[ 'creater' ] ][ 'name' ] );
    $order[ 'creater_name' ] = $this->users[ $order[ 'creater' ] ][ 'name' ];
    $order[ 'sales_name' ] = $this->users[ $order[ 'sales_id' ] ][ 'name' ];
    $order[ 'status_name' ] = $this->status[ $order[ 'status' ] ][ 0 ];

    $list = Db::table( 'order_list' )->where( 'order_id', $all[ 'id' ] )->select()->toArray();
    $num = 0;
    $sum = 0;
    $num_deliv = 0;
    $num_undeliv = 0;

    foreach ( $list as &$kv ) {
        $kv[ 'unit' ] = Db::table( 'goods' )->where( 'id', $kv[ 'goods_id' ] )->value( 'unit' );
        $num += $kv[ 'qty' ];
        $sum += $kv[ 'total' ];
        $kv[ 'price' ] = number_format( $kv[ 'price' ], 4 );
        $kv[ 'total' ] = number_format( $kv[ 'total' ], 4 );

        //本规格已发货数量
        $sum_delivery = Db::query( 'select sum(qty) as qty from delivery_list where delivery_id in(select id from delivery where status=2 and order_id=?) and specs_id=?', [ $kv[ 'order_id' ], $kv[ 'specs_id' ] ] );
        $kv[ 'delivery_qty' ] = ( $sum_delivery[ 0 ][ 'qty' ] )?:0 ;
        $num_deliv += $kv[ 'delivery_qty' ];
        $kv[ 'undelivery_qty' ] = $kv[ 'qty' ]-$kv[ 'delivery_qty' ];
        $num_undeliv += $kv[ 'undelivery_qty' ];
    }

    View::assign( [
        'order' => $order,
        'list' => $list,
        'sys' => $this->sys,
        'num' => $num,
        'sum' => number_format( $sum, 4 ),
        'num_deliv'=>$num_deliv,
        'num_undeliv'=>$num_undeliv,
        'date'=>date( 'Y-m-d' ),
        'uname'=>Session::get( 'uname' ),

    ] );

    return View::fetch( 'order/order_list' );

}


//订单删除

public function order_cancel( $table = '', $id = '' ) {
    $uid = Session::get( 'logonid' );
    if ( empty( $uid ) )
    return json( [ 'code' => 0, 'msg' => '登录已过期' ] );

    $all = Request::param();

    if ( empty( $all[ 'id' ] ) || empty( $all[ 'table' ] ) ) {
        return json( [ 'code' => 0, 'msg' => '参数不正确' ] );
    }
    $name = !empty( $all[ 'name' ] )?$all[ 'name' ]:'订单删除';
    $res = common::row_del( $all[ 'table' ], $all[ 'id' ], $name );

    return $res;
}



//订单详情
public function order_detail() {
    $uid = Session::get( 'logonid' );
    if ( empty( $uid ) )
    return json( [ 'code' => 0, 'msg' => '登录已过期' ] );

    $all = Request::param();

    if ( empty( $all[ 'id' ] ) && empty( $all[ 'order_no' ] ) ) {
        return json( [ 'code' => 0, 'msg' => '订单id参数!' ] );
    }

    if ( !empty( $all[ 'id' ] ) ) {
        $order = Db::table( 'order' )->find( $all[ 'id' ] );
    } elseif ( !empty( $all[ 'order_no' ] ) ) {
        $order = Db::table( 'order' )->where( 'order_no', $all[ 'order_no' ] )->find();
    }
    if ( !$order ) {
        return json( [ 'code'=>0, 'msg'=>'Order ['.$all[ 'order_no' ].'] not found!' ] );
    }

    // halt( $all );
    unset( $order[ 'goods_list' ] );
    //商品描述一栏不要了
    if ( !empty( $all[ 'detail' ] ) ) {
        $order[ 'order_list' ] = Db::table( 'order_list' )->where( 'order_id', $order[ 'id' ] )->select()->toArray();
        foreach ( $order[ 'order_list' ] as &$kv ) {
            $kv[ 'goods_id_name' ] = Db::table( 'goods' )->where( 'id', $kv[ 'goods_id' ] )->value( 'name' );
            $spec_row = Db::table( 'specs' )->where( 'id', $kv[ 'specs_id' ] )->column( 'name,storage' );
            $kv[ 'specs_id_name' ] = $spec_row[ 0 ][ 'name' ];
            $kv[ 'storage' ] = $spec_row[ 0 ][ 'storage' ];

            $sum_delivery = Db::query( 'select sum(qty) as qty from delivery_list where delivery_id in(select id from delivery where status=2 and order_id=?) and specs_id=?', [ $kv[ 'order_id' ], $kv[ 'specs_id' ] ] );
            $kv[ 'delivery_qty' ] = ( $sum_delivery[ 0 ][ 'qty' ] )?:0 ;
            //$num_deliv += $kv[ 'delivery_qty' ];
            $kv[ 'undelivery_qty' ] = $kv[ 'qty' ]-$kv[ 'delivery_qty' ];
            //$num_undeliv += $kv[ 'undelivery_qty' ];
        }

    }

    if ( !empty( $all[ 'delivered_qty' ] ) ) {
        //$order[ 'delivery_qty' ] = Db::query( 'select sum(qty) as qty from delivery where order_id=? and status=2', [ $all[ 'id' ] ] )[ 0 ][ 'qty' ];
        //if ( !$order[ 'delivery_qty' ] ) $order[ 'delivery_qty' ] = 0;
        //halt( $order[ 'delivery_qty' ][ 0 ][ 'qty' ] );
    }
    return json( [ 'code' => 1, 'data' => $order ] );

}
}
